<?php
/**
 * 聊天
 * 
 * Created	: 2011-06-04
 * Modified : 2011-06-04
 * @author  : 陈立强
 */
class Chat
{
	
	/**
	 * 发送聊天信息
	 * @param int $uid
	 * @param string $channel 聊天频道 system-系统通知,world-世界频道,family-家族,team-队伍
	 * @param string $content 聊天的内容
	 * @param int|null $object 聊天的对象,family-家族ID,team-队伍ID
	 */
	public static function send($uid, $channel, $content, $object=null)
	{
		global $m, $G, $L, $DB;
		$pre = 'chat';
		
		$channelList = array(
			'world', 'private'
		);
		if (!in_array($channel, $channelList)) {
			return array(
				'val' => false,
				'msg' => $L['channel_is_not_exist']
			);
		}
		
		// 是否GM命令
		if (User::isGM($uid) && 0 === strpos($content, '@')) {
			$ret = Gm::handleGmCmd($content);
			return array(
				'val' => $ret,
				'data'=> array(array(
						'id'		=> 1,
						'channel'	=> 'world',
						'uid'		=> $uid,
						'nickname'	=> $_SESSION['nickname'],
						'msg'		=> 'Success',
						'args'		=> null
					),
				)
			);
		} elseif ('{refresh_status}' == $content) {//刷新链接状态
			return array(
				'val' => true,
			);
//		} else if (false !== strpos($content, '#')) {
//			$content = toFace($content);
		}
		
		$content = incFileterKw($content);
		// 聊天记录信息
		$chatLog = $m->get('chatLog');
		// 聊天记录存储的最新索引
		$chatIndex = $m->get('chatIndex');
		if (!$chatLog) {
			$chatLog = array();
		}
		if (!$chatLog) {
			$chatIndex = 1;
		} else {
			$chatIndex++;
			
			if ($chatIndex > $G['chat_index_max_val']) {
				$chatIndex = 1;
			}
		}
		$args = null;
		// 私聊
//		if (0 === strpos($content, '/') && false!==($spacePos=strpos($content, ' '))) {
		if ($channel == 'private') {
			$touser = $object;
			if ($touser == $_SESSION['nickname']) {
				return array(
					'val' => false,
					'msg' => $L['cannot_send_self']
				);
			}
			if (!User::isOnline($touser)) {
				return array(
					'val' => false,
					'msg' => $L['user_offline_that_cannot_private_chat']
				);
			}
			$touid = User::readByNickname($touser, 'uid');
			if (!$touid) {
				return array(
					'val' => false,
					'msg' => $L['user_not_exists']
				);
			}
			$sql = 'SELECT ban_chat FROM user_filter WHERE (uid='.$uid.' AND to_uid='.$touid.') OR (uid='.$touid.' AND to_uid='.$uid.')';
			$banChat = $DB->getValue($sql);
			// 黑名单
			if ($banChat) {
				return array(
					'val' => false,
					'msg' => $L['cannot_chat_to_blacklist']
				);
			}
			$args = array(
				'from'		=> $_SESSION['nickname'],
				'to'		=> $touser,
				'to_uid'	=> $touid,
			);
		}
		
		$chatLog[$chatIndex] = array(
			'channel'	=> $channel,
			'uid'		=> $uid,
			'nickname'	=> $_SESSION['nickname'],
			'msg'		=> $content,
			'args'		=> $args
		);
		// 获取聊天记录锁
		$chatLock = $m->get('chatLogLock');
		if ($chatLock) {
			while (true) {
				usleep(100000);//sleep 0.1 second
				$chatLock = $m->get('chatLogLock');
				if (!$chatLock) break;
			}
		}
		//加锁
		$m->set('chatLogLock', true);
		$ret = $m->set('chatLog', $chatLog);
		if ($ret) {
			$ret = $m->set('chatIndex', $chatIndex);
		}
		//解锁
		$m->set('chatLogLock', false);
		
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$newMsg = self::getMsg($uid);
			$result['data'] = $newMsg['data'];
		} else {
			$result['msg'] = $L['Failure'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('chat_send', $str);
		}

		return $result;
	}
	
	/**
	 * 获取最新聊天信息
	 * @param int $uid
	 * @return array
	 */
	public static function getMsg($uid)
	{
		global $m, $G, $DB;
		
		$chatLog = $m->get('chatLog');
		$chatIndex = $m->get('chatIndex');
		$uchatindex = $m->get('uchatindex'.$uid);
		if (empty($uchatindex) || $uchatindex>=$G['chat_index_max_val']) {
			$ui = 0;
		} else {
			$ui = $uchatindex;
		}
//		if ($_SERVER['REMOTE_ADDR'] == '192.168.1.103') {
//			var_export($chatLog);
//			echo "\n";
//			var_dump($ui, $chatIndex);
//			exit;
//		}
		
		// 获取最近登录时间
//		$sql = 'SELECT last_login FROM user WHERE uid='.$uid;
//		$lastLogin = $DB->getValue($sql);

		$sql = 'SELECT to_uid FROM user_filter WHERE uid='.$uid.' AND ban_chat=1';
		$fileterList = $DB->getList($sql);
		
		$msg = array();
		$i = 0;//循环次数
		if ($ui == $chatIndex) {
			$while = false;
		} else {
			$while = true;
		}
		while ($while) {
			$i++;
			$ui++;
			if ($i > $G['chat_index_max_val']) break;
			
			if ($ui > $G['chat_index_max_val']) {
				$ui = 1;
			}
			if (!isset($chatLog[$ui])) {
				$ui++;
				continue;
			}
			$logItem = $chatLog[$ui];
			// 不是发给自己的私聊信息跳过
			if ($logItem['channel'] == 'private') {
				if ($logItem['args']['to']==$_SESSION['nickname'] || $logItem['args']['from']==$_SESSION['nickname']) {
					$logItem['id'] = $ui;
					$msg[] = $logItem;
					// 已经获取的私人信息,要删除
				}
			} else if (in_array($logItem['uid'], $fileterList)) {
				// 拉黑屏蔽用户信息过滤
			} else {
				$logItem['id'] = $ui;
				$msg[] = $logItem;
			}
			
			// 已取到最新信息,跳出循环
			if ($ui == $chatIndex) {
				break;
			}
			
			if ($ui > $G['chat_index_max_val']) {
				$ui=1;
			}
		}
		if ($ui>$G['chat_index_max_val']) {
			$ui = 1;
		}
		$m->set('uchatindex'.$uid, $ui);
//		if ($_SERVER['REMOTE_ADDR'] == '192.168.1.103' && $uid==113) {
//			var_export($msg);
//			echo "\n";
//		}

		if ($m->get('newmail-'.$uid)) {
			$msg[] = array(
				'channel'	=> 'newmail',
				'counts'	=> Mail::getNewMailCounts($uid)
			);
			$m->set('newmail-'.$uid, false);
		}
		
		$result['val'] = true;
		$result['data'] = $msg;

		return $result;
		
	}
}










